import "./login.scss";
import $ from "jquery";
import {getCookie} from "../../libs/common.js";
import Cart from "../../parts/cart/cart";
import ProfileMgr from "../../data/ProfileMgr";

;;(function(){
    let cookie_user = getCookie("username"),
        cookie_pass = getCookie("tocken"),
        loading     = false;
    if(cookie_user && cookie_pass){
        $("#username").val(cookie_user);
        $("#password").val(cookie_pass);
    }

    function changeTipTxt(iptEle,text){
        iptEle.next()
        .css({
            "display": text == "" ? "none" : "inline"
        })
        .children(".warn")
        .html(text);
    }
    function requestLogin(){
        let username = $("#username").val(),
            password = $("#password").val();
        
        if(username.length <= 0){
            changeTipTxt($("#username"),"请输入用户名");
            return false;
        }
        if(password.length <= 0){
            changeTipTxt($("#password"),"请输入密码");
            return false;
        }
        if(loading) return false;
        loading = true;
        $.ajax("http://59.110.157.147/server/group8Interface/login.php",{
            type: "POST",
            data: {
                username ,
                password,
                author: "dbp"
            }
        })
        .then(res=>{
            loading = false;
            res = JSON.parse(res);
            if(res.status === "success"){
                setTimeout( a => {
                    // 跳转到主页页面
                    location.href = "../../index.html";
              },2000);
            }
            else if(res.status === "error"){
                changeTipTxt($("#password"),"用户名或密码错误!");
            }
        })
    };

    function bindEvent(){
        $("#username").focus(function(){
            changeTipTxt($(this),"");
        });
        $("#password").focus(function(){
            changeTipTxt($(this),"");
        });
        $("#myForm").submit(function(){
            return false;
        });
        $("#reg_submit").click(requestLogin);
    }

    $(function(){
        // 购物车
        ProfileMgr.repeatLoad();
        $('.web_head').load('./header.html',function(){
            new Cart();
        });
        $('.footer').load('./footer.html');
        bindEvent();
    });
})();